package com.pwt.scheduled;

import com.pwt.entity.PowerModule;
import com.pwt.entity.WERTEVAR;
import com.pwt.model.ShiftModel;
import com.pwt.model.what.OverviewModel;
import com.pwt.repository.PowerModuleRepository;
import com.pwt.repository.WERTEVARRepository;
import com.pwt.service.FilterUnitService;
import com.pwt.service.MERKMALCONTROLService;
import com.pwt.utils.CommonUtils;
import com.pwt.utils.DoubleUtils;
import com.pwt.utils.MathUtil;
import com.pwt.utils.SigmaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author dw
 * @date 2021/12/17 9:45
 * @Description
 */
@Component
@Slf4j
public class CrustallusScheduled {

    private WERTEVARRepository wertevarRepository;

    private PowerModuleRepository powerModuleRepository;

    private MERKMALCONTROLService merkmalcontrolService;

    public CrustallusScheduled(WERTEVARRepository wertevarRepository, PowerModuleRepository powerModuleRepository, MERKMALCONTROLService merkmalcontrolService) {
        this.wertevarRepository = wertevarRepository;
        this.powerModuleRepository = powerModuleRepository;
        this.merkmalcontrolService = merkmalcontrolService;
    }

    @Scheduled(cron = "0 0 */2 * * ?")
    @Transactional
    public void controlScheduled(){
        this.merkmalcontrolService.updateControlMerkmal();
    }



    // 每半小时执行一次
    //@Scheduled(cron = "0 29 22 ? * *")
    //@Async
    //@Scheduled(fixedDelay = 1000 * 60 * 60)
    public void  scheduledPowerModule(){
        //最后跟新班次时间
        try {
            log.info("定时器开始执行-----------------------------------------------");
            Date minTime = wertevarRepository.queryMinWVDATZEIT();
            Date lastTime = wertevarRepository.queryMaxWVDATZEIT();
            if(minTime.before(lastTime)){
                ShiftModel shiftModel = CommonUtils.getNowClass(minTime);
                savePowerModule(shiftModel);
                //跟新班次最后时间
                while (shiftModel.getEndTime().before(lastTime)){
                    shiftModel = getNestClass(shiftModel.getEndTime());
                    savePowerModule(shiftModel);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void savePowerModule(ShiftModel shiftModel){

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTime = dateFormat.format(shiftModel.getStartTime());
        String endTime = dateFormat.format(shiftModel.getEndTime());
        List<PowerModule> insert = new ArrayList<>();
        //机器和零件类型分组
        List<PowerModule> powerList = this.wertevarRepository.queryMASCHINE(beginTime,endTime);
        if(powerList == null || powerList.size()< 1) return;
        for(PowerModule power:powerList){
            power.setBeginTime(shiftModel.getStartTime());
            power.setEndTime(shiftModel.getEndTime());
            PowerModule newPower = this.groupClass(power,beginTime,endTime);
            insert.add(newPower);
        }
        this.powerModuleRepository.deleteByBeginTimeAndEndTime(shiftModel.getStartTime(),shiftModel.getEndTime());
        this.powerModuleRepository.saveAllAndFlush(insert);
    }

    public ShiftModel getNestClass(Date endTime){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
        ShiftModel shiftModel = new ShiftModel();
        shiftModel.setStartTime(endTime);
        calendar.setTime(endTime);
        calendar.add(Calendar.HOUR,12);
        shiftModel.setEndTime(calendar.getTime());
        return shiftModel;
    }


    
    public PowerModule groupClass(PowerModule pm,String beginTime,String endTime){
        List<OverviewModel>  characterList= this.wertevarRepository.getCharacteristicsByOrderId(pm.getK2005(),pm.getK0010(), beginTime,endTime,pm.getK0053(),pm.getK1000());
        if(characterList != null && characterList.size() > 0 ){
            for (OverviewModel character:characterList) {
                if(character.getK2111() == null || character.getK2110() == null) {
                    pm.setOk(pm.getOk()+1);
                    continue;
                };
                //根据被测参数 获取 测量值
                List<Double> values = this.wertevarRepository.getValueByOrderId(pm.getK0010(),character.getK1000(),character.getK2000(), beginTime, endTime,pm.getK0053());
                if(values == null || values.size() < 1) continue;
                Double avg = MathUtil.avg(values);
                Double down = character.getK2110();
                Double up = character.getK2111();
                Double sigma = SigmaUtil.getSigma(values,avg);
                Double T = up - down;

                //cp
                Double  cp= MathUtil.divDouble(T,6*sigma);

                Double cpu = MathUtil.divDouble((up - avg) ,3*sigma);

                Double cpl = MathUtil.divDouble((avg - down) , 3*sigma);
                //cpk
                Double cpk = Math.min(cpu,cpl);
                // 判断状态  产品是否合格
                if(cp >= character.getCpTarget()
                        && cpk >= character.getCpkTarget()){
                    if(values.size() <= 40){
                        pm.setSomeok(pm.getSomeok()+1);
                    }else{
                        pm.setOk(pm.getOk()+1);
                    }
                }else{
                    pm.setNok(pm.getNok()+1);
                }

            }
        }

        if(pm.getOk() == 0 && pm.getSomeok() == 0 && pm.getNok() == 0){
            pm.setStatus(0);
        }
        return pm;
    }
}
